package com.example.keepmesafe.activities;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.keepmesafe.R;
import com.example.keepmesafe.domain.KeepMeAuthectication;
import com.example.keepmesafe.repository.DBHelper;
import com.example.keepmesafe.service.AESCrypto;
import com.example.keepmesafe.service.UtilService;
import com.example.keepmesafe.service.impl.UtilServiceImpl;

public class UserLogin extends Activity {
	static final String LOG_TAG = "UserLogin";
	final Context ctx = this;
	final DBHelper tagStorageImpl = new DBHelper(ctx);
	final UtilService service = new UtilServiceImpl();
	final AESCrypto crypto = new AESCrypto();
	Handler handler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_login);
		Button loginButton = (Button)findViewById(R.id.loginUserK);
		Button setupButton = (Button)findViewById(R.id.setupUser);
		final EditText email = (EditText)findViewById(R.id.email);
		final EditText master = (EditText)findViewById(R.id.masterPass);
		
//		Toast.makeText(ctx, ""+SQLiteDatabase.deleteDatabase(new File("/data/data/com.example.keepmesafe/databases/kms.db")), Toast.LENGTH_SHORT).show();
		//check if user has registered if so hide the login button or setup button
		SQLiteDatabase initialDB = tagStorageImpl.getWritableDatabase();
		Cursor results = initialDB.rawQuery("select * from auth", null);
		String globalMaster = getMasterFromCursor(results);
		
		if(!globalMaster .equals("empty")){
			//means there is a phrase in the database so user needs to login
			setupButton.setVisibility(View.GONE);
			email.setVisibility(View.GONE);
		}else{
			//means there is no phrase in the database so user needs to register
			loginButton.setVisibility(View.GONE);
		}
		initialDB.close();
		//if registering setOnCLickListener For User
		setupButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setupUser();
			}
		});
		//if login setOnCLickListener For User
		loginButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				loginUser(master);
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
		 Log.i(LOG_TAG,"onBackPressed--");
	}
	
	public void setupUser(){
		Log.i(LOG_TAG,"setting up user from view");
		KeepMeAuthectication authectication = new KeepMeAuthectication();
		EditText master = (EditText)findViewById(R.id.masterPass);
		EditText email = (EditText)findViewById(R.id.email);
			try {
				authectication.setMasterPassword(crypto.encrypt(master.getText().toString()));
				authectication.setEmailAddress(crypto.encrypt(email.getText().toString()));
				//save Auth to database
				saveToDbFromAuth(authectication);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public void saveToDbFromAuth(KeepMeAuthectication authectication){
		Log.i(LOG_TAG,"saving to the database");
		
		if((authectication.getEmailAddress()!=null&&!authectication.getEmailAddress().equals(""))
			&& authectication.getMasterPassword()!=null&&!authectication.getMasterPassword().equals("")){
			
			SQLiteDatabase initialDBS =  tagStorageImpl.getWritableDatabase();
			ContentValues authValues = new ContentValues();
			authValues.put("masterPassword", authectication.getMasterPassword()); 
			authValues.put("recoveryEmail", authectication.getEmailAddress());
			initialDBS.insertOrThrow("auth", null, authValues);
			initialDBS.close();
			Intent goToUserHomeAct = new Intent(this, UserHome.class);
			startActivity(goToUserHomeAct);
		}else if(authectication.getEmailAddress()==null||authectication.getEmailAddress().equals("")){
			Toast.makeText(ctx, "Please enter a email address ", Toast.LENGTH_LONG).show();
		}else if(authectication.getMasterPassword()==null||authectication.getMasterPassword().equals("")){
			Toast.makeText(ctx, "Please enter a master password", Toast.LENGTH_LONG).show();
		}
	}

	public void loginUser(EditText master){
		Log.i(LOG_TAG,"getting details from the database");
		try{
			SQLiteDatabase initialDBS = tagStorageImpl.getWritableDatabase();
			Cursor authUser = initialDBS.rawQuery("select * from auth", null);
			String masterSaved = getMasterFromCursor(authUser);  
			if(!masterSaved.equals("empty")){
				String masterPassword = crypto.encrypt(master.getText().toString());
				initialDBS.close();
				if(masterPassword.equals(masterSaved)){
					Intent goToUserHomeAct = new Intent(this, UserHome.class);
					startActivity(goToUserHomeAct);
				}else{
					TextView error = (TextView)findViewById(R.id.errorMessage);
					error.setText("The master password is incorrect");
					master.setText("");
					master.setFocusable(true);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	public String getMasterFromCursor(Cursor authUser){  
		
		while(authUser.moveToNext()){
			return authUser.getString(1);
		}
		return "empty";
	}
	
}
